import { BookModel } from '../../models/book.js'
import { LikeModel } from '../../models/like.js'
let bookModel = new BookModel()
let likeModel = new LikeModel()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    comments: [],
    book: null,
    likeStatus: false,
    likeCount: 0,
    posting: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.showLoading()
    const bid = options.bid
    const bookDetail = bookModel.getDetail(bid)
    const comment = bookModel.getComment(bid)
    const likeStatus = bookModel.getLikeStatus(bid)

    //三个请求同时发送成功后才赋值，并隐藏loading状态
    Promise.all([bookDetail, comment, likeStatus])
      .then(res => {
        console.log(res)
        this.setData({
          book: res[0],
          comments: res[1].comments,
          likeStatus: res[2].like_status,
          likeCount: res[2].fav_nums
        })
        wx.hideLoading()
      })
    // bookDetail.then(res=>{
    //   console.log(res)
    //   this.setData({
    //     book: res
    //   })
    // })

    // comment.then(res => {
    //   console.log(res)
    //   this.setData({
    //     comments: res.comments
    //   })
    // })

    // likeStatus.then(res => {
    //   console.log(res)
    //   this.setData({
    //     likeStatus: res.like_status,
    //     likeCount: res.fav_nums
    //   })
    // })
  },
  onLike(event) {
    console.log(event)
    let val = event.detail.typeClick
    likeModel.getLike(val, this.data.book.id, 400)
  },

  onFakePost() {
    this.setData({
      posting: true
    })
  },

  onCancel() {
    this.setData({
      posting: false
    })
  },

  onPost(event) {
    console.log(event)
    let text = event.detail.text || event.detail.value
    if (!text) return
    if (text.length > 12) {
      wx.showToast({
        title: '短评最多12个字',
        icon: 'none'
      })
      return
    }
    bookModel.postComment(this.data.book.id, text)
      .then(res => {
        wx.showToast({
          title: '+ 1',
          icon: 'none'
        })

        this.data.comments.unshift({
          content: text,
          nums: 1
        })
        this.setData({
          comments: this.data.comments,
          posting: false
        })
      })

  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})